package com.tieba.util;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.List;
import java.util.Random;

public class Utils {

	public static int getRandom(int min, int max) {
		Random random = new Random();
		int s = random.nextInt(max) % (max - min + 1) + min;
		return s;
	}

	public static String list2String(List<String> list) {
		StringBuffer sb = new StringBuffer();
		for (String s : list) {
			sb.append(s).append(";");
		}
		return sb.toString();
	}

	public static String String2URLDecode(String text) {
		try {
			text = URLEncoder.encode(text, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return text;
	}

	public static String URLDecode2String(String text) {
		try {
			text = URLDecoder.decode(text, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return text;
	}

	public static void main(String[] args) throws Exception {

		// System.out.println(Utils.String2URLDecode("图拉丁"));
		// System.out.println(URLDecode2String("%E5%A4%8D%E4%BB%87%E8%80%85%E8%81%94%E7%9B%9F"));
		// System.out.println(URLDecode2String(String2URLDecode("图拉丁")));

		System.out.println(URLEncoder.encode("图拉丁", "UTF-8"));

	}

	public static boolean StrIsNull(String str) {
		if (str == null || str.length() <= 0) {
			return true;
		} else {
			return false;
		}
	}

	public static boolean StrNotNull(String str) {
		if (str != null && str.length() != 0) {
			return true;
		} else {
			return false;
		}
	}

	public static Long Str2Long(String str) {
		try {
			return Long.parseLong(str);
		} catch (Exception e) {
			return null;
		}
	}

	public static String Long2Str(Long str) {
		try {
			return str.toString();
		} catch (Exception e) {
			return null;
		}
	}

	public final static String MD5(String s) {
		try {
			byte[] btInput = s.getBytes();
			MessageDigest mdInst = MessageDigest.getInstance("MD5");
			mdInst.update(btInput);
			byte[] md = mdInst.digest();
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < md.length; i++) {
				int val = ((int) md[i]) & 0xff;
				if (val < 16)
					sb.append("0");
				sb.append(Integer.toHexString(val));

			}
			return sb.toString();
		} catch (Exception e) {
			return null;
		}
	}

	public final static String MD5Encoder(String s, String charset) {
		try {
			byte[] btInput = s.getBytes(charset);
			MessageDigest mdInst = MessageDigest.getInstance("MD5");
			mdInst.update(btInput);
			byte[] md = mdInst.digest();
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < md.length; i++) {
				int val = ((int) md[i]) & 0xff;
				if (val < 16) {
					sb.append("0");
				}
				sb.append(Integer.toHexString(val));
			}
			return sb.toString();
		} catch (Exception e) {
			return null;
		}
	}
}
